<template>
  <div
    ref="chartRef"
    :style="{ width: width, height: height }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
const props = defineProps({
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '400px',
  },
  options: {
    type: Object,
    required: true,
  },
})
const chartRef = ref(null)
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  chartInstance.setOption(props.options, true)
}

const resizeChart = () => {
  chartInstance && chartInstance.resize()
}

onMounted(() => {
  window.addEventListener('resize', resizeChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  chartInstance && chartInstance.dispose()
})

watch(() => props.options, initChart, { deep: true })
</script>
